<template>
  <view class="overdue-container">

    <!-- 顶部导航栏 -->
    <view class="nav-header">
      <view class="nav-title">
        <view class="back-icon" @click="goBack">
          <uni-icons type="left" size="20"></uni-icons>
        </view>
        <view class="title-text">代收逾期</view>
        <view class="nav-actions">
          <view class="search-icon">
            <uni-icons type="search" size="20" @click="showSearch"></uni-icons>
          </view>
        </view>
      </view>
    </view>

    <!-- 筛选条件区域 -->
    <filter-bar :filters="['department', 'billType', 'filter']" :filter-data="filterData"
      @filter-change="handleFilterChange"></filter-bar>

    <!-- 账单列表 -->
    <scroll-view scroll-y class="bill-list" @scrolltolower="loadMore">
      <view class="bill-item" v-for="(item, index) in billList" :key="index">
        <view class="bill-content">
          <view class="bill-info">
            <view class="bill-title">{{ item.title }}</view>
            <view class="bill-detail">
              <text class="date">{{ item.date }}</text>
              <text class="tenant">| {{ item.tenant }}</text>
            </view>
            <view class="bill-status">
              <text class="days-overdue">逾期{{ item.overdueDays }}天</text>
            </view>
          </view>
          <view class="bill-amount">
            <text class="amount">¥{{ item.amount }}</text>
            <text class="status">{{ item.status }}</text>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view class="loading" v-if="isLoading">
        <text>加载中...</text>
      </view>
      <view class="no-more" v-if="noMore">
        <text>没有更多数据了</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import NavBar from '@/components/nav-bar/index.vue';
import FilterBar from '@/components/filter-bar/index.vue';
import { getOverdueBillList } from '@/api/overdue.js';
import { formatDate, formatAmount } from '@/utils/index.js';

export default {
  components: {
    NavBar,
    FilterBar
  },
  data() {
    return {
      billList: [],
      isLoading: false,
      noMore: false,
      page: 1,
      pageSize: 10,
      currentFilters: {},
      // 添加筛选数据
      filterData: {
        department: [
          {
            value: 'dept1',
            label: '总部',
            children: [
              { value: 'user1', label: '张三' },
              { value: 'user2', label: '李四' }
            ]
          },
          {
            value: 'dept2',
            label: '分部',
            children: [
              { value: 'user3', label: '王五' },
              { value: 'user4', label: '赵六' }
            ]
          }
        ],
        billType: [
          { value: 'all', label: '不限' },
          { value: 'rent', label: '租约' },
          { value: 'deposit', label: '押金' },
          { value: 'earnest', label: '定金' },
          { value: 'extra', label: '加收费用' },
          { value: 'earnest_refund', label: '退定结算' },
          { value: 'rent_refund', label: '退租结算' },
          { value: 'accounting', label: '记账' },
          { value: 'meter', label: '仪表' }
        ],
        filter: [
          {
            title: '逾期天数',
            type: 'overdueDays',
            options: [
              { value: '0-7', label: '7天内' },
              { value: '8-30', label: '8-30天' },
              { value: '31-90', label: '31-90天' },
              { value: '90+', label: '90天以上' }
            ]
          },
          {
            title: '金额区间',
            type: 'amountRange',
            options: [
              { value: '0-1000', label: '1000元以下' },
              { value: '1000-5000', label: '1000-5000元' },
              { value: '5000-10000', label: '5000-10000元' },
              { value: '10000+', label: '10000元以上' }
            ]
          }
        ]
      }
    }
  },
  onLoad() {
    this.loadBillList();
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    showSearch() {
      uni.navigateTo({
        url: '/pages/overdue/search'
      });
    },
    // 更新筛选处理方法
    handleFilterChange(params) {
      console.log('Filter changed:', params);
      
      // 更新筛选参数
      this.currentFilters = {};
      
      if (params.department) {
        this.currentFilters.department = params.department;
      }
      
      if (params.billType) {
        this.currentFilters.billType = params.billType;
      }
      
      if (params.filter && params.filter.length) {
        params.filter.forEach(item => {
          if (item.type === 'overdueDays') {
            this.currentFilters.overdueDays = item.value;
          } else if (item.type === 'amountRange') {
            this.currentFilters.amountRange = item.value;
          }
        });
      }
      
      // 重置分页并加载数据
      this.page = 1;
      this.billList = [];
      this.noMore = false;
      this.loadBillList();
    },
    async loadBillList() {
      if (this.isLoading) return;
      this.isLoading = true;
      
      try {
        // 构建请求参数
        const params = {
          page: this.page,
          pageSize: this.pageSize,
          // 添加筛选参数
          department: this.currentFilters?.department || '',
          billType: this.currentFilters?.billType || 'all',
          overdueDays: this.currentFilters?.overdueDays || '',
          amountRange: this.currentFilters?.amountRange || ''
        };
        
        // 发起API请求
        const result = await getOverdueBillList(params);
        console.log('API response:', result);
        
        // 处理响应数据
        if (result && result.data && result.data.list) {
          const formattedData = result.data.list.map(item => ({
            id: item.id,
            title: item.title || `账单${item.id}`,
            date: formatDate(item.date),
            tenant: item.tenant || '未知',
            overdueDays: item.overdueDays || 0,
            amount: item.amount,
            status: item.status || '待收'
          }));
          
          this.billList = [...this.billList, ...formattedData];
          
          // 判断是否还有更多数据
          this.noMore = !result.data.hasMore;
        } else {
          // 处理空数据情况
          if (this.page === 1) {
            this.billList = [];
          }
          this.noMore = true;
        }
      } catch (error) {
        console.error('加载账单列表失败:', error);
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        });
      } finally {
        this.isLoading = false;
      }
    },
    loadMore() {
      if (this.noMore || this.isLoading) return;
      this.page++;
      this.loadBillList();
    }
  }
}
</script>

<style lang="scss">
.overdue-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.nav-header {
  background-color: #fff;
  padding: 20rpx 30rpx;
  height: 80rpx;
  box-sizing: border-box;
  position: sticky;
  top: var(--window-top);
  z-index: 1000;

  .nav-title {
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;

    .back-icon {
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 44rpx;
      height: 44rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .title-text {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }

    .nav-actions {
      display: flex;
      align-items: center;
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);

      .search-icon {
        margin-left: 30rpx;
        width: 44rpx;
        height: 44rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}

.bill-list {
  padding: 20rpx;
  height: calc(100vh - 180rpx);
  box-sizing: border-box;
}

.bill-item {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.bill-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20rpx;
}

.bill-info {
  flex: 1;
  min-width: 0;

  .bill-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 16rpx;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .bill-detail {
    font-size: 26rpx;
    color: #666;
    margin-bottom: 12rpx;

    .tenant {
      margin-left: 16rpx;
    }
  }

  .bill-status {
    .days-overdue {
      font-size: 24rpx;
      color: #ff4d4f;
      background-color: #fff1f0;
      padding: 4rpx 12rpx;
      border-radius: 4rpx;
    }
  }
}

.bill-amount {
  text-align: right;
  min-width: 180rpx;
  flex-shrink: 0;

  .amount {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    display: block;
    margin-bottom: 8rpx;
    white-space: nowrap;
  }

  .status {
    font-size: 24rpx;
    color: #ff4d4f;
    background-color: #fff1f0;
    padding: 4rpx 12rpx;
    border-radius: 4rpx;
    white-space: nowrap;
  }
}

.loading,
.no-more {
  text-align: center;
  padding: 20rpx;
  color: #999;
  font-size: 24rpx;
}
</style>